package com.example.wnn.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 媒体格式转换
 */
@Slf4j
public class MediaConvertUtils {

    /**
     * 视频文件转音频文件
     *
     * @param videoPath
     * @param audioPath return true or false
     */
    public static void videoToAudio(String videoPath, String audioPath) throws Exception {
        File fileMp4 = new File(videoPath);
        File fileMp3 = new File(audioPath);

        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libmp3lame");
        audio.setBitRate(128000);
        audio.setChannels(2);
        audio.setSamplingRate(44100);

        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setOutputFormat("mp3");
        attrs.setAudioAttributes(audio);
        Encoder encoder = new Encoder();
        MultimediaObject mediaObject = new MultimediaObject(fileMp4);
        encoder.encode(mediaObject, fileMp3, attrs);

    }


    /**
     * @param downloadUrl     下载链接
     * @param targetDirectory 下载到的目录
     * @param fileName        下载后的文件名称
     * @return
     * @throws Exception
     */
    public static boolean download(String downloadUrl, String targetDirectory, String fileName) throws Exception {
        // 解决url中可能有中文情况
        URL url = new URL(downloadUrl);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setConnectTimeout(3000);
        // 设置 User-Agent 避免被拦截
        http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
        String contentType = http.getContentType();
        // 获取文件大小
        long length = http.getContentLengthLong();
        // 获取文件名
        InputStream inputStream = http.getInputStream();
        byte[] buff = new byte[1024 * 10];
        File file = new File(targetDirectory, fileName);
        if (!file.exists()) {
            OutputStream out = new FileOutputStream(file);
            int len;
            int count = 0; // 计数
            while ((len = inputStream.read(buff)) != -1) {
                out.write(buff, 0, len);
                out.flush();
                ++count;
            }
            // 关闭资源
            out.close();
            inputStream.close();
            http.disconnect();
            return true;
        }
        return false;
    }

    public static boolean delFile(String path) {
        boolean flag = false;
        try {
            //根据路径创建文件对象
            File file = new File(path);
            //路径是个文件且不为空时删除文件
            if (file.isFile() && file.exists()) {
                flag = file.delete();
            }
        } catch (Exception exception) {
            log.error("delFile_error:{}", exception.getMessage());
        }
        //删除失败时，返回false
        return flag;
    }


    public static void videoToAudio(String downloadUrl, String targetDirectory, String fileName) {
        String errorMsg = "";
        boolean downloadSuccess = false;
        boolean convertSuccess = false;
        try {
            downloadSuccess = download(downloadUrl, targetDirectory, fileName);
        } catch (Exception downloadException) {
            errorMsg = String.format("下载文件异常,文件下载地址:%s,目标文件夹:%s,错误原因:%s", downloadUrl, targetDirectory, downloadException.getMessage());
            log.info(errorMsg);
        }
        if (downloadSuccess) {
            log.info("下载文件成功:{},开始转换成MP3格式", downloadSuccess);
            String completeFileName = targetDirectory + "/" + fileName;
            String audioPath = completeFileName + ".mp3";
            try {
                videoToAudio(completeFileName, audioPath);
                convertSuccess = true;
            } catch (Exception convertException) {
                errorMsg = String.format("转换文件异常,文件地址:%s,预计转换文件:%s,错误原因:%s", completeFileName, audioPath, convertException.getMessage());
                log.info(errorMsg);
            }
            //删除下载的文件
            delFile(completeFileName);
        }
    }


    public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int) file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }





    /*  public static void main(String[] args) {
     *//*    String fileName =  "38abb56dbc014d3d8f79f16a8afa1d65_"+System.currentTimeMillis();
        String downloadUrl ="https://health-test-dev.s3.cn-north-1.jdcloud-oss.com/20221219/38abb56dbc014d3d8f79f16a8afa1d65.mp4";
        String targetDirectory = "/Users/wenzheng/Desktop/MediaConvert";
        videoToAudio(downloadUrl,targetDirectory,fileName);*//*
        String a = "/Users/wenzheng/Desktop/MediaConvert/c002_1671614565414.mp3";
        File file = new File(a);
        MultipartFile multipartFile = getMultipartFile(file);
        System.out.println(multipartFile.toString());

    }
*/

    public static String getContentBrowser(Integer browser) {

        if (browser == null || browser == 0) {
            return "1";
        } else {
            browser = browser + 1;
        }

        int paramBrowser = browser.intValue();

        if (paramBrowser < 1000) {
            return String.valueOf(paramBrowser);
        } else {
            BigDecimal num = new BigDecimal(paramBrowser).divide(new BigDecimal("10000")).setScale(2,BigDecimal.ROUND_HALF_UP).stripTrailingZeros();

            DecimalFormat df = new DecimalFormat();

            df.applyPattern("0.00");

            return df.format(num) + "万";
        }
    }
    public static void main(String[] args) {
        List<Integer> list= Arrays.asList(1000001,1000002,1000003,1000004,1000005,1000006);
        String s =list.stream().map(String::valueOf).collect(Collectors.joining(","));
        System.out.println(s);
        List<String> ls = Arrays.asList(s.split(","));
        System.out.println(ls);

        t();
//        t1();
//        t2();

        BigDecimal avgAmount = new BigDecimal("899.00").multiply(new BigDecimal("0.05"))
                .divide(new BigDecimal(2)).setScale(2, RoundingMode.HALF_UP);
        //22.4750
        System.out.println(avgAmount);

        t();

//        System.out.println(plusDay(0));
//        System.out.println(plusDay(null));
//        System.out.println(plusDay(2));
        Long a = 1710716147000L;
        Long b = a+1;
        if (a<b){
            System.out.println("a<b");

        }

    }

    public static String plusDay(Integer num){
        if (Objects.isNull(num)){
            num = 0;
        }
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currdate = format.format(d);
      //  log.info("现在的日期是：" + currdate);

        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
        d = ca.getTime();
        String enddate = format.format(d);
      //  log.info("增加天数以后的日期：" + enddate);
        return enddate;
    }



    public static void t(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 2); // 将日期设置为前一天
        Date yesterday = calendar.getTime();
        String dateStr = sdf.format(yesterday);
        DateTime dateTime = DateUtil.parse(dateStr);
        System.out.println(dateTime.getTime()/1000);
    }
    public static void t1(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1); // 将日期设置为前一天
        Date yesterday = calendar.getTime();
        String dateStr = sdf.format(yesterday);
        DateTime dateTime = DateUtil.parse(dateStr);
        System.out.println(dateTime.getTime()/1000);
    }

    public static void t2(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1); // 将日期设置为前一天
        Date yesterday = calendar.getTime();
        String dateStr = sdf.format(yesterday);
        System.out.println(dateStr);
    }
}
